package controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	public static String sendHttpPostMessage(String Url,
			List<NameValuePair> param) {

		String sResult = "";
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(Url);
			httppost.setHeader("Content-type",
					"application/x-www-form-urlencoded");
			if ((param != null) && (param.size() > 0)) {
				try {
					httppost.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			HttpResponse httpResponse = client.execute(httppost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				ByteArrayOutputStream bytearrayoutputstream;
				InputStream inputstream;
				byte abyte0[] = new byte[1024];
				bytearrayoutputstream = new ByteArrayOutputStream();
				inputstream = httpResponse.getEntity().getContent();
				int nRead = 0;
				while ((nRead = inputstream.read(abyte0)) != -1) {
					bytearrayoutputstream.write(abyte0, 0, nRead);
				}
				inputstream.close();
				sResult = new String(bytearrayoutputstream.toByteArray(),
						"utf-8");
				bytearrayoutputstream.close();
			}
			client.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sResult;
	}

	public static String sendHttpGetMessage(String Url) {
		String sResult = "";
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(Url);
			httpget.setHeader("Content-type",
					"application/x-www-form-urlencoded");
			HttpResponse httpResponse = client.execute(httpget);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				sResult = EntityUtils.toString(httpResponse.getEntity());
			}
			client.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sResult;
	}
}
